<!--
 * @Descripttion: 
 * @version: 
 * @Author: weni09
 * @Date: 2021-04-13 10:36:48
 * @LastEditors: weni09
 * @LastEditTime: 2021-04-14 10:37:22
 * @FilePath: \blogfastapi\apps\frontend_admin\src\components\WangEditor.vue
-->
<template>
       <div class="editor" ></div>
</template>

<script>
// 引入 wangEditor
import wangEditor from 'wangeditor'
import hljs from 'highlight.js'
import 'highlight.js/styles/solarized-light.css'

export default {
  name: "editorElem",
  data() {
    return {
      editor: null,
      editorData: ''
    }
  },
  props: {
     value: {
        type: String,
        default: ''
      },
  },
  watch: {
    'value'(val) {
      if (val) {
        if (val !== this.editorData) {
          this.setContent(val);
        }
      } else {
        this.setContent('');
      }
    },
      'editorData'(val) {
        if (val && val !== this.value) {
          // 编辑器内容发生变化时，告知外部，实现 v-model 双向监听效果
          // console.log(val)
          this.$emit('input', val)
        }
      },
  },
  mounted() {
    const editor = new wangEditor(`.editor`)
    // this.editor = new wangEditor(this.$refs.editorElem)
    // 配置 onchange 回调函数，将数据同步到 vue 中
    editor.config.onchange = html => {
      this.editorData = html
    };
    // 配置 server 接口地址
    editor.config.uploadImgServer = global.API_URI + 'upload-img'
    // 限制图片大小
    editor.config.uploadImgMaxSize = 1 * 1024 * 1024
    // 限制一次最多能传几张图片
    editor.config.uploadImgMaxLength = 5 // 一次最多上传 5 个图片
    //自定义 header
    editor.config.uploadImgHeaders = {
    Authorization: "Bearer " + this.$store.state.auth.token
    }
    // withCredentials（跨域传递 cookie)
    editor.config.withCredentials = false
    // 自定义 fileName,这里指后端收到的file对象名称
    editor.config.uploadFileName = 'uploadimg'
    //隐藏插入网络图片的功能
    editor.config.showLinkImg = false
    // 忽略粘贴内容中的图片,主要过滤掉外域路径，图片会自动上传回显
    editor.config.pasteIgnoreImg = true
    // 配置alt选项
    editor.config.showLinkImgAlt = true
    // 配置超链接
    editor.config.showLinkImgHref = false
    // 配置菜单栏，设置不需要的菜单
    editor.config.excludeMenus = ['video']
    // 挂载highlight插件
    editor.highlight = hljs
    
    // 创建编辑器
    editor.create()
    // console.log(editor.id)
    //获取传递过来的value,没有显示空
    // console.log(this.value,!this.value)
    if (!this.value){
        editor.txt.html('')
    }
    else{
        editor.txt.html(this.value)
    }
  },
  methods: {
    setContent(val) {
      this.editor.txt.html(val)
    }
  },
  // beforeDestroy() {
  //   // 销毁编辑器
  //   this.editor.destroy()
  //   // this.editor = null
  // },
}
</script>

<style lang="scss">
 .editor {
    width: 100%;
    height: 300px;
    margin: 0;
    position: relative;
  }
</style>
